<template>
	<div>
		<nav-bar />
		<category-item 
			:data="myCategoryData" 
			title="现有栏目"
			@remove="removeCategory"
		/>
		
		<category-item 
			:data="orderCategoryData"
			title="已删除栏目"
			color="#fb7299"
			@add="addCategory"
		 />
	</div>
</template>

<script>
	import { getCategory } from '@/api'
	import NavBar from '@/components/common/NavBar.vue'
	import CategoryItem from './categoryItem.vue'
	export default {
		name: 'editcategory',
		data () {
			return {
				// 我的频道
				myCategoryData: [],
				// 其他频道
				orderCategoryData: []
			}
		},
		created() {
			this.myCategoryData = JSON.parse(window.localStorage.getItem('myCategoryData'))
			this.orderCategoryData = JSON.parse(window.localStorage.getItem('orderCategoryData')) || []
			
			const myCategoryData = window.localStorage.getItem('myCategoryData')
			// 查看是否有缓存
			if (!myCategoryData) {
				this._getCategory()
			} 
			
		},
		methods: {
			// 获取分类信息
			_getCategory() {
				// 发送请求
				getCategory()
				.then(res => {
					console.log('分类信息',res)
					// 判断状态码
					if (res.status !== 200) return this.$toast.fail('请求异常,请重新尝试!')
					window.localStorage.setItem('myCategoryData',JSON.stringify(res.data))
					this.myCategoryData = JSON.parse(window.localStorage.getItem('myCategoryData'))
				})
				.catch(err => {
					this.$toast.fail('请求异常,请重新尝试!')
				})
			},
			// 添加栏目
			addCategory(index) {
				this.myCategoryData.unshift(this.orderCategoryData[index])
				this.orderCategoryData.splice(index,1)
				window.localStorage.setItem('myCategoryData',JSON.stringify(this.myCategoryData))
				window.localStorage.setItem('orderCategoryData',JSON.stringify(this.orderCategoryData))
			},
			// 移除栏目
			removeCategory(index) {
				if (this.myCategoryData.length < 4) return this.$toast('最少保留三个')
				this.orderCategoryData.unshift(this.myCategoryData[index])
				this.myCategoryData.splice(index,1)
				window.localStorage.setItem('myCategoryData',JSON.stringify(this.myCategoryData))
				window.localStorage.setItem('orderCategoryData',JSON.stringify(this.orderCategoryData))
			}
		},
		components: {
			NavBar,
			CategoryItem
		}
	}
</script>

<style lang="scss" scoped>
	
</style>